package com.simba.server.components;

import com.simba.server.base.CommonUtil;
import com.simba.server.commands.impl.web.WebSortInfoCmd;
import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import com.simba.server.components.data.SortInfo;

import java.util.List;
import java.util.stream.Collectors;

public class BarcodeManager
{
	private static class BarcodeManagerHolder
	{
		private static final BarcodeManager INSTANCE = new BarcodeManager();
	}

	protected static final Logger logger = Logger.getLogger(BarcodeManager.class);

	public static BarcodeManager getInstance()
	{
		return BarcodeManagerHolder.INSTANCE;
	}

	private BarcodeManager()
	{

	}

	public boolean checkBarcodeListValid(SortInfo info){
		List<String> barcodeList = info.getBarcodeList();
		if (!SorterParams.getInstance().isMultiCodeCheck()){
			return true;
		}

		if (barcodeList.isEmpty())
		{
			return false;
		}

		if (barcodeList.size() <= 1){
			return true;
		}

		List<String> list= barcodeList.stream().distinct().collect(Collectors.toList());

		if (list.size() <= 1){
			return true;
		}

		List<Integer> slots = null;
		String normalBarcode = null;
		for (String barcode: list) {
			SortInfo sortInfo = SortInfoManager.getInstance().createSortInfo();
			sortInfo.setBarcode(barcode);

			boolean res = CommandExecutor.executorWebCommand(WebSortInfoCmd.NAME, sortInfo,false);
			if (res){
				if (slots == null){
					normalBarcode = barcode;
					slots = sortInfo.getSlotsList();
				}else {
					if (!CommonUtil.equalLists(slots, sortInfo.getSlotsList())){
						return false;
					}
				}
			}
		}

		if (normalBarcode != null){
			info.setBarcode(normalBarcode);
		}else{
			return false;
		}

		return true;
	}

	public boolean checkBarcodeValid(String barcode)
	{
		if (!SorterParams.getInstance().isCheckBarcode()){
			return true;
		}

		boolean ret;

		try
		{
			// ret = barcode.matches(this.packageRegex);
			ret = true;
		}
		catch (Exception e)
		{
			ret = false;
		}

		return ret;
	}

	public void init()
	{

	}
}
